import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:io';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'dart:async';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '抽奖程序',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: LotteryScreen(),
    );
  }
}

class LotteryScreen extends StatefulWidget {
  const LotteryScreen({super.key});

  @override
  State<LotteryScreen> createState() => _LotteryScreenState();
}

class _LotteryScreenState extends State<LotteryScreen> {
  List<String> _allNames = [];
  List<String> _remainingNames = [];
  List<String> _winners = [];
  Map<int, List<String>> _winnerperson = {};
  int _drawCount = 1;
  final Random _random = Random();
  final TextEditingController _drawCountController = TextEditingController();
  bool _isRolling = false;
  bool _isStopped = false;
  bool _canConfirm = false;
  List<String> _currentShowNames = []; 
  int _maxColumns = 5;
  Timer? _rollingTimer;
  

  @override
void dispose() {
  _rollingTimer?.cancel();
  super.dispose();
}


  // 平台自适应文件读取
  Future<String> _readFileContent(PlatformFile file) async {
    try {
      // Web端处理
      if (kIsWeb) {
        if (file.bytes == null) throw Exception('文件内容为空');
        return utf8.decode(file.bytes!);
      }
      // 移动端/桌面端处理
      else {
        if (file.path == null) throw Exception('文件路径无效');
        final fileObj = File(file.path!);
        return await fileObj.readAsString();
      }
    } catch (e) {
      throw Exception('文件读取失败: ${e.toString()}');
    }
  }

  Future<void> _importNames() async {
    try {
      // 移动端权限检查
      if (!kIsWeb) {
        final status = await Permission.storage.request();
        if (!status.isGranted) {
          throw Exception('需要文件访问权限');
        }
      }

      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['txt', 'csv'],
        allowMultiple: false,
        withData: true, // 确保Web端获取字节数据
      );

      if (result == null || result.files.isEmpty) return;

      final file = result.files.first;
      print('[DEBUG] 选择文件: ${file.name} (${file.size} bytes)');

      // 读取文件内容
      final content = await _readFileContent(file);
      print('[DEBUG] 文件内容:\n$content');
      if (!mounted) return;

      final names =
          content
              .split('\n')
              .map((e) => e.trim())
              .where((e) => e.isNotEmpty)
              .toList();
      if (!mounted) return;

      if (names.isEmpty) throw Exception('文件中没有有效姓名');

      setState(() {
        _allNames = names;
        _remainingNames = List.from(names);
        _winners.clear();
        _winnerperson.clear();
      });
      if (!mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('成功导入 ${names.length} 个姓名')));
    } catch (e) {
      print('[ERROR] 导入失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('错误: ${e.toString().replaceAll('Exception: ', '')}'),
        ),
      );
    }
  }

   void _validateAndSetDrawCount(String value) {
    if (value.isEmpty) {
      _drawCount = 1;
      return;
    }
    
    final number = int.tryParse(value);
    if (number == null || number <= 0) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('请输入有效的正整数'))
      );
      _drawCountController.text = _drawCount.toString();
      return;
    }
    if (number > _remainingNames.length) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('抽奖人数不能超过剩余人数'))
      );
      _drawCountController.text = _drawCount.toString();
      return;
    }
     setState(() {
      _drawCount = number;
    });
  }
  void _handleStart() {
  if (_remainingNames.isEmpty || _drawCount > _remainingNames.length) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('抽奖人数不足，无法开始'))
    );
    return;
  }

  setState(() {
    _isRolling = true;
    _isStopped = false;
    _canConfirm = false;
  });

  // 启动定时器刷新展示区
  _rollingTimer?.cancel();
  _rollingTimer = Timer.periodic(Duration(milliseconds: 100), (timer) {
    final tempList = List<String>.from(_remainingNames)..shuffle();
    setState(() {
      _currentShowNames = tempList.sublist(0, min(_drawCount, tempList.length));
    });
  });
}

void _handleStop() {
  setState(() {
    _isRolling = false;
    _isStopped = true;
    _canConfirm = true;
  });
  _rollingTimer?.cancel();
}

// void _confirmWinners() {
//   if (_currentShowNames.isEmpty) return;
//   setState(() {
//     // 从剩余名单中移除中奖者
//     _remainingNames.removeWhere((name) => _currentShowNames.contains(name));
    
//     // 添加到中奖列表
//     final round = _winnerperson.length + 1;
//     _winnerperson[round] = List.from(_currentShowNames);
//     _winners.addAll(_currentShowNames);
    
//     // 重置展示区
//     _currentShowNames.clear();
//     _isRolling = false;
//     _isStopped = false;
//   });
// }

void _handleConfirm() {
  if (_currentShowNames.isEmpty) return;

  setState(() {
    _remainingNames.removeWhere((name) => _currentShowNames.contains(name));
    _winners.addAll(_currentShowNames);
    final round = _winnerperson.length + 1;
    _winnerperson[round] = List.from(_currentShowNames);
    
    _currentShowNames.clear();
    _isRolling = false;
    _isStopped = false;
    _canConfirm = false;
  });

  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text('已确认 ${_currentShowNames.length} 位中奖者'))
  );
}

  // void _startDraw() {
  //   try {
  //     if (!mounted) return;
  //     if (_remainingNames.isEmpty) throw Exception('没有可抽奖的人员');
  //     if (_drawCount <= 0 || _drawCount > _remainingNames.length) {
  //       throw Exception('抽奖人数无效');
  //     }

  //     setState(() {
  //       final selected = <String>[];
  //       for (int i = 0; i < _drawCount; i++) {
  //         final index = _random.nextInt(_remainingNames.length);
  //         selected.add(_remainingNames.removeAt(index));
  //       }
  //       _winners.addAll(selected);
  //       int roundtimes = _winnerperson.length;
  //       _winnerperson[roundtimes + 1] = selected;
  //     });
  //   } catch (e) {
  //     ScaffoldMessenger.of(
  //       context,
  //     ).showSnackBar(SnackBar(content: Text(e.toString())));
  //   }
  // }

  void _reset() {
    setState(() {
      _remainingNames = List.from(_allNames);
      _winners.clear();
      _winnerperson.clear();
    });
  }

   Widget _buildNumberPresetButtons() {
    final presets = [1, 2, 3, 5, 10];
    return Wrap(
      spacing: 8,
      children: presets.map((number) {
        return ChoiceChip(
          label: Text('$number 人'),
          selected: _drawCount == number,
          onSelected: (selected) {
            if (selected) {
              _drawCountController.text = number.toString();
              _validateAndSetDrawCount(number.toString());
            }
          },
        );
      }).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('多轮抽奖程序'),
        actions: [
          IconButton(
            icon: Icon(Icons.info_outline),
            onPressed:
                () => showDialog(
                  context: context,
                  builder:
                      (ctx) => AlertDialog(
                        title: Text('使用说明'),
                        content: Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('1. 点击右上角导入按钮选择TXT/CSV文件'),
                            Text('2. 每行一个姓名，支持中文'),
                            Text('3. 设置每次抽取人数后点击开始抽奖'),
                            Text('4. 中奖者会自动从候选池移除'),
                          ],
                        ),
                        actions: [
                          TextButton(
                            child: Text('确定'),
                            onPressed: () => Navigator.pop(ctx),
                          ),
                        ],
                      ),
                ),
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 控制面板
            _buildControlPanel(),
            SizedBox(height: 20),

            // 统计信息
            _buildStatsGrid(),
            SizedBox(height: 20),

          _buildRollingDisplay(),  // 新增的展示区
          _buildActionButtons(),    // 修改后的按钮组

            // // 抽奖按钮
            // ElevatedButton(
            //   onPressed: _startDraw,
            //   style: ElevatedButton.styleFrom(
            //     shape: RoundedRectangleBorder(
            //       borderRadius: BorderRadius.circular(8),
            //     ),
            //   ),
            //   child: Padding(
            //     padding: EdgeInsets.symmetric(vertical: 16),
            //     child: Text('开始抽奖', style: TextStyle(fontSize: 18)),
            //   ),
              
            // ),
            SizedBox(height: 10),

            // 重置按钮
            TextButton(onPressed: _reset, child: Text('重置抽奖池')),
            SizedBox(height: 20),

            // 中奖列表
            Expanded(child: _buildWinnerList()),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _importNames,
        tooltip: '导入名单',
        child: Icon(Icons.upload_file),
      ),
    );
  }

  Widget _buildControlPanel() {
    return Row(
      children: [
        Expanded(
          child: TextField(
                    controller: _drawCountController,
                    keyboardType: TextInputType.number,
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    decoration: InputDecoration(
                      labelText: '每次抽取人数',
                      border: OutlineInputBorder(),
                      suffixIcon: IconButton(
                        icon: Icon(Icons.info_outline),
                        onPressed: () => showDialog(
                          context: context,
                          builder: (ctx) => AlertDialog(
                            title: Text('提示'),
                            content: Text('请输入1到${_remainingNames.length}之间的整数'),
                          ),
                        ),
                      ),
                    ),
                    onChanged: (value) => _validateAndSetDrawCount(value),
                    onSubmitted: (value) => _validateAndSetDrawCount(value),
                  ),
        ),
                SizedBox(height: 12),
                Text('快捷选择:', style: TextStyle(color: Colors.grey[600])),
                _buildNumberPresetButtons(),
      ],
    );
  }

  Widget _buildStatsGrid() {
    return GridView.count(
      shrinkWrap: true,
      crossAxisCount: 3,
      childAspectRatio: 7,
      children: [
        _buildStatCard('总人数', _allNames.length),
        _buildStatCard('剩余人数', _remainingNames.length),
        _buildStatCard('已中奖', _winners.length),
      ],
    );
  }

  Widget _buildStatCard(String title, int value) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(2.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(title, style: TextStyle(color: Colors.grey)),
            SizedBox(height: 2),
            Text(
              '$value',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
                color: Colors.blue,
              ),
            ),
          ],
        ),
      ),
    );
  }

Widget _buildWinnerList() {
  return Card(
    elevation: 4,
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
    child: Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(12.0),
          child: Text(
            '中奖名单',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
        ),
        Expanded(
          child: _winners.isEmpty
              ? Center(
                  child: Text(
                    '暂无中奖者',
                    style: TextStyle(color: Colors.grey),
                  ),
                )
              : SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    children: _winnerperson.entries.map((entry) {
                      final round = entry.key;
                      final roundWinners = entry.value;
                      return Container(
                        width: 250,
                        padding: const EdgeInsets.all(12.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '第 $round 轮',
                              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                            ),
                            Expanded(
                              child: ListView.separated(
                                padding: EdgeInsets.zero,
                                shrinkWrap: true,
                                // physics: NeverScrollableScrollPhysics(),
                                itemCount: roundWinners.length,
                                separatorBuilder: (_, __) => Divider(height: 1),
                                itemBuilder: (ctx, winnerIndex) {
                                  final name = roundWinners[winnerIndex];
                                  final initials = getInitials(name);
                                  return ListTile(
                                    leading: CircleAvatar(
                                      backgroundColor: Colors.blue.shade100,
                                      child: Text(initials),
                                    ),
                                    title: Text(name),
                                    trailing: Icon(
                                      Icons.celebration,
                                      color: Colors.orange,
                                    ),
                                  );
                                },
                              ),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ),
        ),
      ],
    ),
  );
}

Widget _buildActionButtons() {
  return Column(
    children: [
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
           ElevatedButton(
        onPressed: _isRolling && !_isStopped ? null : () => _handleStart(),
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue,
          foregroundColor: Colors.white,
        ),
        child: Text(_isStopped ? '重新开始' : '开始'),
      ),
          ElevatedButton(
        onPressed: _isRolling && !_isStopped ? () => _handleStop() : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.red,
          foregroundColor: Colors.white,
        ),
        child: Text('停止'),
        
      ),
       ElevatedButton(
        onPressed: _canConfirm ? () => _handleConfirm() : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.green,
          foregroundColor: Colors.white,
        ),
        child: Text('确认'),
      ),
        ],
      ),
      Text(
        '当前模式：每次抽取 $_drawCount 人',
        style: TextStyle(color: Colors.grey),
      ),
    ],
  );
}

Widget _buildRollingDisplay() {
  return Container(
    constraints: BoxConstraints(maxHeight: 200),
    margin: EdgeInsets.symmetric(vertical: 16),
    padding: EdgeInsets.all(8),
    decoration: BoxDecoration(
      border: Border.all(color: Colors.blue),
      borderRadius: BorderRadius.circular(8),
    ),
    child: SingleChildScrollView(
      child: Wrap(
        alignment: WrapAlignment.center,
        spacing: 10,
        runSpacing: 10,
        children: _currentShowNames.map((name) {
          return Container(
            width: (MediaQuery.of(context).size.width - 60) / _maxColumns,
            padding: EdgeInsets.symmetric(vertical: 8, horizontal: 4),
            decoration: BoxDecoration(
              color: Colors.blue.withOpacity(0.1),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Center(
              child: Text(
                name,
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue[800],
                ),
                textAlign: TextAlign.center,
              ),
            ),
          );
        }).toList(),
      ),
    ),
  );
}

// Widget _buildNameBox(String name) {
//   return Container(
//     width: 100,
//     padding: EdgeInsets.all(8),
//     decoration: BoxDecoration(
//       color: Colors.blue.withOpacity(0.1),
//       borderRadius: BorderRadius.circular(4),
//     ),
//     child: Center(
//       child: Text(
//         name,
//         style: TextStyle(
//           fontSize: 20,
//           fontWeight: FontWeight.bold,
//           color: Colors.blue[800],
//         ),
//       ),
//     ),
//   );
// }


}

String getInitials(String name) {
  String initials = '';
  List<String> parts = name.split(' ');
  for (String part in parts) {
    if (part.isNotEmpty) {
      initials += part[0].toUpperCase();
    }
  }
  return initials;
}